package com.example.administrator.social.fragment;


import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.administrator.social.activitys.MyInfoHeaderSettingsActivity;
import com.example.administrator.social.R;
import com.example.administrator.social.activitys.SettingsActivity;
import com.example.administrator.social.model.User;
import com.example.administrator.social.util.AllenUtils;
import com.example.administrator.social.util.HttpUtils;
import com.example.administrator.social.util.request.CustomRequest;
import com.google.gson.Gson;

import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyInfoFragment extends Fragment implements View.OnClickListener {
    Context mContext;
    TextView mPhoneText,mNickNameText,mSexText,mAgeText,mEmailText,mQcCodeText,
            mMoreText,mSettingsText;
    ImageView mHeaderImage;
    RelativeLayout mHeaderLayout;
    String mUserName;
    //http
    RequestQueue mRequestQueue;


    public MyInfoFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getContext();
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_my_info, container, false);
        initView(view);
        SharedPreferences preferences = mContext.getSharedPreferences("user", Context.MODE_PRIVATE);
        mUserName = preferences.getString("name","");
        mRequestQueue =  Volley.newRequestQueue(mContext);
        doHttpRequestGetData();
        return view;
    }

    private void initView(View view) {
        mSettingsText = view.findViewById(R.id.myinfo_settings_text);
        mNickNameText = view.findViewById(R.id.myinfo_nick_name);
        mSexText = view.findViewById(R.id.myinfo_sex_text);
        mPhoneText = view.findViewById(R.id.myinfo_phone_text_view);
        mAgeText = view.findViewById(R.id.myinfo_age_text);
        mEmailText = view.findViewById(R.id.myinfo_email_text);
        mMoreText = view.findViewById(R.id.myinfo_more_text);
        mHeaderImage = view.findViewById(R.id.myinfo_header_image);
        mQcCodeText = view.findViewById(R.id.myinfo_qr_code_text);
        mHeaderLayout = view.findViewById(R.id.myinfo_header_layout);
        mSettingsText.setOnClickListener(this);
        mSexText.setOnClickListener(this);
        mAgeText.setOnClickListener(this);
        mEmailText.setOnClickListener(this);
        mMoreText.setOnClickListener(this);
        mQcCodeText.setOnClickListener(this);
        mHeaderLayout.setOnClickListener(this);
    }

    private void doHttpRequestGetData() {
        String url = HttpUtils.HTTP_URL+"getUserInfo?name="+mUserName;
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                updateUserInfoUI(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(mContext,"网络异常!",Toast.LENGTH_SHORT).show();
            }
        });
        mRequestQueue.add(request);
    }

    private void updateUserInfoUI(String response) {
        System.out.println(response);
        User user = new Gson().fromJson(response, User.class);
        if (user==null){
            return;
        }
        if (user.getHeader_image()==null||user.getHeader_image().equals("")){
            Glide.with(mContext).load(HttpUtils.HTTP_URL+"img/defualt_header_icon.jpeg").into(mHeaderImage);
        }else{
            Glide.with(mContext).load(user.getHeader_image()).into(mHeaderImage);
        }
        if (user.getNick_name()!=null&&!"".equals(user.getNick_name())){
            mNickNameText.setText(user.getNick_name());
        }else{
            mNickNameText.setText(user.getName());
        }
        if(user.getSex()!=null){
            mSexText.setText(getResources().getString(R.string.sex)+user.getSex());
        }
        if(user.getEmail()!=null){
            mEmailText.setText(getResources().getString(R.string.email)+user.getEmail());
        }
        if(user.getAge()!=null){
            mAgeText.setText(getResources().getString(R.string.age)+user.getAge());
        }
        mPhoneText.setText(user.getPhone());

        //存入用户信息。
        AllenUtils.saveSharedPreferencesObjData(mContext,"user_info","user",user);
    }




    @Override
    public void onClick(View v) {
        int i = v.getId();
        switch (i){
            case R.id.myinfo_header_layout:
                Intent intent = new Intent(mContext,MyInfoHeaderSettingsActivity.class);
                intent.putExtra("name",mNickNameText.getText());
                intent.putExtra("phone",mNickNameText.getText());
                startActivity(intent);
                break;
            case R.id.myinfo_sex_text:
                showDialog("sex");
                break;
            case R.id.myinfo_age_text:
                showDialog("age");
                break;
            case R.id.myinfo_email_text:
                showDialog("email");
                break;
            case R.id.myinfo_qr_code_text:
                break;
            case R.id.myinfo_more_text:
                break;
            case R.id.myinfo_settings_text:
                startActivity(new Intent(mContext, SettingsActivity.class));
                break;

            /*sex dialog*/
            case R.id.myinfo_sex_man:
            case R.id.myinfo_sex_woman:
            case R.id.myinfo_sex_kept:
                sendRequestUpdateSex(String.valueOf(v.getTag()));
                break;
                /*email dialog*/
            case R.id.myinfo_set_email_button:
                sendRequestUpdateEmail(String.valueOf(v.getTag()));
                break;
        }
    }

    /**
     * update Email
     * @param value
     */
    private void sendRequestUpdateEmail(final String value) {
        mDialog.dismiss();
        String url = HttpUtils.HTTP_URL+"updateUserInfo";
        CustomRequest request = new CustomRequest(url, Request.Method.POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println("sendRequestUpdateEmail response = " + response);
                mEmailText.setText(R.string.email + value);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("sendRequestUpdateEmail volleyError = " + volleyError);
            }
        });
        Map<String,String> map = new HashMap<>();
        map.put("name",mUserName);
        map.put("change_content","email");
        map.put("new_value",value);
        request.setParamsMap(map);
        mRequestQueue.add(request);

    }

    /**
     * update Sex
     * @param value
     */
    private void sendRequestUpdateSex(final String value) {
        mDialog.dismiss();
        String url = HttpUtils.HTTP_URL+"updateUserInfo";
        CustomRequest request = new CustomRequest(url, Request.Method.POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println("sendRequestUpdateSex response = " + response);
                mSexText.setText(R.string.sex + value);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("sendRequestUpdateSex volleyError = " + volleyError);
            }
        });
        Map<String,String> map = new HashMap<>();
        map.put("name",mUserName);
        map.put("change_content","sex");
        map.put("new_value",value);
        request.setParamsMap(map);
        mRequestQueue.add(request);
    }

    AlertDialog mDialog;
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void showDialog(String style) {
        if(style.equals("sex")){
            mDialog = new AlertDialog.Builder(mContext,R.style.style_dialog).create();
            View layout = View.inflate(mContext, R.layout.myinfo_setsex_dialog_layout, null);
            TextView manText = layout.findViewById(R.id.myinfo_sex_man);
            TextView womanText = layout.findViewById(R.id.myinfo_sex_woman);
            TextView keptText = layout.findViewById(R.id.myinfo_sex_kept);
            manText.setTag("man");
            womanText.setTag("women");
            keptText.setTag("kept");
            manText.setOnClickListener(this);
            womanText.setOnClickListener(this);
            keptText.setOnClickListener(this);
            Window window = mDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);
            window.getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(lp);
            mDialog.setView(layout);
            mDialog.create();
            mDialog.show();
        }else if(style.equals("age")){
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(calendar.YEAR);
            int monthOfYear = calendar.get(calendar.MONTH);
            int dayOfMonth = calendar.get(calendar.DAY_OF_MONTH);
            DatePickerDialog  dialog = new DatePickerDialog(getActivity(), android.app.AlertDialog.THEME_HOLO_LIGHT,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                String str = year+"-"+month+"-"+dayOfMonth;
                                System.out.println("showDialog str = " + str);
                                int age = AllenUtils.getAgeFromBirthTime(AllenUtils.stringToDate(str,"yyyy-MM-dd"));
                                if (String.valueOf(age).equals(mAgeText.getText())){
                                    return;
                                }
                                //sendRequest updateInfo
                                Message message = Message.obtain();
                                message.what = 1;
                                message.arg1 = age;
                                message.obj = str;
                                mHandler.sendMessage(message);
                            }
                        },year, monthOfYear, dayOfMonth);
            dialog.create();
            dialog.show();
        }else if(style.equals("email")){
            mDialog = new AlertDialog.Builder(mContext).create();
            View layout = View.inflate(mContext, R.layout.myinfo_set_email_dialog_layout, null);
            EditText emailEdit =  layout.findViewById(R.id.myinfo_set_email_input_edit);
            Button setEmailButton = layout.findViewById(R.id.myinfo_set_email_button);
            setEmailButton.setTag(emailEdit.getText());
            setEmailButton.setOnClickListener(this);
            Window window = mDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            mDialog.setView(layout);
            mDialog.create();
            mDialog.show();
        }
    }


    /**
     *
     * 根据后台接口.
     * Post参数:name->用户名，
     * change_content->需要修改的字段、信息，
     * new_value-->需要更新的值。
     * @param age
     */
    private void updateUserAge(int age) {
        String url = HttpUtils.HTTP_URL+"updateUserInfo";
        CustomRequest request = new CustomRequest(url, Request.Method.POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println("updateUserInfo  response = " + response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("updateUserInfo  volleyError = " + volleyError);
            }
        });
        Map<String,String> map = new HashMap<>();
        map.put("name",mUserName);
        map.put("change_content","age");
        map.put("new_value",String.valueOf(age));
        request.setParamsMap(map);
        mRequestQueue.add(request);
    }

    /**更新用户生日
     * 根据后台接口.
     * Post参数:name->用户名，
     * change_content->需要修改的字段、信息，
     * new_value-->需要更新的值。
     * @param obj
     */
    private void updateUserBirth(Object obj) {
        String birth = String.valueOf(obj);
        String url = HttpUtils.HTTP_URL+"updateUserInfo";
        CustomRequest request = new CustomRequest(url, Request.Method.POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println("updateUserBirth  response = " + response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("updateUserBirth  volleyError = " + volleyError);
            }
        });
        Map<String,String> map = new HashMap<>();
        map.put("name",mUserName);
        map.put("change_content","birth");
        map.put("new_value",birth);
        request.setParamsMap(map);
        mRequestQueue.add(request);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    updateUserAge(msg.arg1);
                    updateUserBirth(msg.obj);
                    break;
                case 2:
            }
        }
    };



}
